package com.binguo.wxapi.service;

import com.alibaba.fastjson.JSONObject;
import com.binguo.common.util.UrlUtils;
import com.binguo.model.api.vo.WXMessageVO;
import com.binguo.model.mapper.BinguoOrderMapper;
import com.binguo.model.mapper.CustomerMapper;
import com.binguo.model.mapper.ShopPushMsgMapper;
import com.binguo.model.model.BinguoOrder;
import com.binguo.model.model.Customer;
import com.binguo.model.model.ShopPushMsg;
import com.binguo.model.model.ShopPushMsgExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MessagePushService {

    @Resource
    private ShopPushMsgMapper shopPushMsgMapper;
    @Resource
    private CustomerMapper customerMapper;
    @Resource
    private BinguoOrderMapper binguoOrderMapper;
    private static Logger logger = LoggerFactory.getLogger(MessagePushService.class);
    public final static String appid = "wx099356561cb9c60f";
    public final static String secret ="5af8b26fd8bedd5779131116468b419f";
    public static String accessToken;

    /**
     * 获取AccessToken  不确定AccessToken是会随时间或者用户变化还是不会，如果会，则下面的定时推送还需要先获取AccessToken
     * @return
     */
    public Map getAccessToken(){
        Map<String,String> map = new HashMap<>();
        map = UrlUtils.getAccessToken(appid,secret);
        accessToken = map.get("access_token");
        return map;
    }

    /**
     * 主动推送消息
     * @param wxMessageVO
     * @return
     * @throws IOException
     */
    public Map sendMessage(WXMessageVO wxMessageVO)throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser",wxMessageVO.getTouser());
        jsonObject.put("template_id",wxMessageVO.getTemplateId());
        jsonObject.put("data",wxMessageVO.getData());
        Map<String,String> map = new HashMap<>();
        map = UrlUtils.send2("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+wxMessageVO.getAccessToken(),jsonObject,"utf-8");
        return map;
    }

    /**
     * 获取商户推送设置信息
     * @param shopId
     * @return
     */
    public ShopPushMsg getShopMessageStatus(Integer shopId){
        ShopPushMsgExample example = new ShopPushMsgExample();
        ShopPushMsgExample.Criteria criteria = example.createCriteria();
        criteria.andShopidEqualTo(shopId);
        List<ShopPushMsg> shopPushMsgs = shopPushMsgMapper.selectByExample(example);
        if(null != shopPushMsgs){
            return shopPushMsgs.get(0);
        }else{
            return null;
        }

    }

    /**
     * 定时推送方法(模板还未申请)
     * 模板配置:orderId   订单id
     *          amount   支付金额
     *          payType  支付类型
     *          payTime  支付时间
     *          comments 备注
     * @throws IOException
     */
    public void sendMessageByTime()throws IOException{
        ShopPushMsgExample example = new ShopPushMsgExample();
        ShopPushMsgExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(2);
        //查找出所有的定时推送的商户
        List<ShopPushMsg> shopPushMsgs = shopPushMsgMapper.selectByExample(example);
        //根据商户查找出所有的需要推送的用户
        //存储所有的免费推送商户
        List<Integer> shopIdsfree = new ArrayList<>();
        //存储所有的付费推送商户
        List<Integer> shopIdspay = new ArrayList<>();
        for(ShopPushMsg shopPushMsg: shopPushMsgs){
            if(shopPushMsg.getPayType()==0){
                shopIdsfree.add(shopPushMsg.getShopid());
            }else{
                shopIdspay.add(shopPushMsg.getShopid());
            }
        }
        //查找出付费推送的商户和免费推送的商户对应的用户列表
        List<Customer> freeCustomer = customerMapper.selectPushMessageCustomerFree(shopIdsfree);
        List<Customer> payCustomer = customerMapper.selectPushMessageCustomerPay(shopIdspay);
        List<Customer> customers = new ArrayList<>();
        customers.addAll(freeCustomer);
        customers.addAll(payCustomer);
        //根据用户列表查询出用户前一个小时所有的订单
        List<BinguoOrder> binguoOrders = binguoOrderMapper.findOrdersByCustomer(freeCustomer);
        binguoOrders.addAll(binguoOrderMapper.findOrdersByCustomer(payCustomer));
        JSONObject jsonObject = new JSONObject();
        //查询出所有的订单之后进行消息推送
        for(BinguoOrder binguoOrder : binguoOrders){
            WXMessageVO wxMessageVO = new WXMessageVO();
            for(Customer customer : customers){
                if(customer.getId()==binguoOrder.getCustomerid()){
                    jsonObject.put("touser",customer.getOpenid());
                }
            }
            jsonObject.put("template_id","写死(这里还没申请)");
            JSONObject data = new JSONObject();
            data.put("orderId",binguoOrder.getOrderno());
            data.put("amount",binguoOrder.getRealfee());
            if(binguoOrder.getSource() == 0){
                data.put("payType","二维码支付");
            }else if(binguoOrder.getSource() == 1){
                data.put("payType","人脸支付");
            }else if(binguoOrder.getSource() == 2){
                data.put("payType","实体卡支付");
            }else if(binguoOrder.getSource() == 3){
                data.put("payType","其他支付");
            }else if(binguoOrder.getSource() == 4){
                data.put("payType","被扫支付");
            }
            data.put("payTime",binguoOrder.getPaytime());
            if(binguoOrder.getIsMeals()==1 && binguoOrder.getIsWarm() == 0){
                data.put("comments","存餐不加热");
            }else if(binguoOrder.getIsMeals()==1 && binguoOrder.getIsWarm() == 1){
                data.put("comments","存餐并加热");
            }else{
                data.put("comments","不存餐不加热");
            }
            jsonObject.put("data",data);
            jsonObject.put("data",wxMessageVO.getData());
            logger.info(jsonObject.toJSONString());
            UrlUtils.send2("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+accessToken,jsonObject,"utf-8");
        }

    }

    /**
     * 更新商户推送设置
     * @param shopPushMsg
     * @return
     */
    public Integer updateShopMessageStatus(ShopPushMsg shopPushMsg){
        return shopPushMsgMapper.updateByPrimaryKeySelective(shopPushMsg);
    }

}
